package com.mrd.shiptask_shipowner.activity;

import java.util.HashMap;
import java.util.Map;

import com.mrd.shiptask_shipowner.R;
import com.mrd.shiptask_shipowner.constants.HttpConstant;
import com.mrd.shiptask_shipowner.constants.database.DBUtil;
import com.mrd.shiptask_shipowner.serviecs.BizNetworkService;
import com.mrd.shiptask_shipowner.serviecs.initdatadao.InitDatasDaoImpl;
import com.mrd.shiptask_shipowner.shiareutil.SharePreferenceUtil;
import com.mrd.shiptask_shipowner.unit_tools.ButtonTool;
import com.mrd.shiptask_shipowner.unit_tools.FunctionOfActivity;
import com.mrd.shiptask_shipowner.unit_tools.HttpUrlConstant;
import com.mrd.shiptask_shipowner.unit_tools.SysApplication;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class ElectronManifestActivity extends Activity {

	/** 全局的LayoutInflater对象，已经完成初始化. */
	public LayoutInflater mInflater;
	private final ElectronManifestActivity THIS = ElectronManifestActivity.this;
	private WebView webView;
	String uri;
	private Button submitContractBt, submitNoContractBt, backToBeforeBt6,
			requestCancelBt;
	private TextView toBeConfirmedTv;
	private SharePreferenceUtil spu;
	ProgressDialog pro;
	private String thisEleId;
	private String ownerConfirm;
	private String shipperConfirm;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_electron_manifest);
		// 页面加载完毕前提示
		showProgressDialog();
		spu = new SharePreferenceUtil(THIS, HttpConstant.SAVE_USER);
		// 如果是推送进来的
		if (getIntent().hasExtra("getPushValueOfKey")) {
			thisEleId = getIntentValue("getPushValueOfKey");
			initContentFromPush();
		} else {
			thisEleId = getIntentValue("eleId");
		}
		initQueryRodeCount();
		initView();
		SysApplication.getInstance().addActivity(this);
	}

	private void initQueryRodeCount() {
		HashMap<String, Object> param = new HashMap<String, Object>();
		param.put("ship", spu.getShip_id());
		param.put("eleId", thisEleId);
		new Thread(new BizNetworkService(THIS, handler,
				HttpUrlConstant.GET_ELE_QUERY_RODE_COUNT, param)).start();
	}

	private void initContentFromPush() {
		try {
			pro = new ProgressDialog(THIS);
			// TODO Auto-generated method stub
			pro.setMessage("正在为您加载内容信息，请稍候");
			pro.show();
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("ship_id", spu.getShip_id());
			param.put("eleId", thisEleId);
			new Thread(new BizNetworkService(THIS, handler,
					HttpUrlConstant.INIT_TOONEELE_BY_ID, param)).start();
		} catch (Exception e) {
			pro.dismiss();
		}
	}

	private void showProgressDialog() {
		FunctionOfActivity.makeToaskShow(THIS, "加载页面中，请耐心等待");
	}

	private void initView() {
		TextView topTitleTv = (TextView) findViewById(R.id.topTitleTv);
		topTitleTv.setText("运输合同");
		submitContractBt = (Button) findViewById(R.id.submit_contract_button);
		submitNoContractBt = (Button) findViewById(R.id.submit_noContract_button);
		backToBeforeBt6 = (Button) findViewById(R.id.backToBeforeBt6);
		requestCancelBt = (Button) findViewById(R.id.request_cancel_button);
		requestCancelBt.setOnClickListener(socl);
		backToBeforeBt6.setOnClickListener(socl);
		submitContractBt.setOnClickListener(socl);
		submitNoContractBt.setOnClickListener(socl);
		toBeConfirmedTv = (TextView) findViewById(R.id.to_be_confirmed);
		String getShipperConfirm = getIntentValue("getSHIPPER_CONFIRM");
		String getOwnerConfirm = getIntentValue("getOWNER_CONFIRM");
		// 如果是推送进来的
		if (getIntent().hasExtra("getPushValueOfKey")) {
			getShipperConfirm = DBUtil.getConfirmFromDBByType(THIS,
					getIntentValue("getPushValueOfKey"), "shipper");
			getOwnerConfirm = DBUtil.getConfirmFromDBByType(THIS,
					getIntentValue("getPushValueOfKey"), "ownner");
		}
		// 赋值全局变量，申请取消时使用
		ownerConfirm = getOwnerConfirm;
		shipperConfirm = getShipperConfirm;
		if ("2".equals(getOwnerConfirm)) {
			// 货主取消
			submitContractBt.setVisibility(View.GONE);
			requestCancelBt.setVisibility(View.GONE);
			submitNoContractBt.setVisibility(View.GONE);
			toBeConfirmedTv.setText("货主已取消该合同");
			toBeConfirmedTv.setBackgroundColor(getResources().getColor(
					R.color.already_reject));

		} else if ("0".equals(getOwnerConfirm)) {
			toBeConfirmedTv.setText("等待货主确认合同");
			submitContractBt.setVisibility(View.GONE);
			submitNoContractBt.setVisibility(View.GONE);
			if ("3".equals(getShipperConfirm)) {
				toBeConfirmedTv.setText("申请取消合同审核中");
			}
		} else {
			submitContractBt.setVisibility(View.GONE);
			submitNoContractBt.setVisibility(View.GONE);
			if ("1".equals(getShipperConfirm)) {
				toBeConfirmedTv.setBackgroundColor(getResources().getColor(
						R.color.already_con));
				toBeConfirmedTv.setText("您已同意此合同");
				requestCancelBt.setVisibility(View.GONE);
			} else if ("2".equals(getShipperConfirm)) {
				toBeConfirmedTv.setBackgroundColor(getResources().getColor(
						R.color.already_reject));
				toBeConfirmedTv.setText("您已驳回此合同");
			} else if ("0".equals(getShipperConfirm)) {
				toBeConfirmedTv.setVisibility(View.GONE);
				submitContractBt.setVisibility(View.VISIBLE);
				submitNoContractBt.setVisibility(View.VISIBLE);
			}
		}
		ButtonTool.onClickButtonStyle(THIS, new Button[] { submitContractBt,
				submitNoContractBt });
		initWebView(thisEleId);
	}

	protected final OnClickListener socl = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			switch (arg0.getId()) {
			case R.id.submit_contract_button:
				new AlertDialog.Builder(THIS)
						.setTitle("是否确认同意条款？")
						.setIcon(android.R.drawable.ic_dialog_info)
						.setPositiveButton("同意",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										try {
											Map<String, Object> param = new HashMap<String, Object>();
											param.put("id", thisEleId);
											param.put("ship_id",
													spu.getShip_id());
											param.put("reason", "123");
											param.put("redoCount",
													spu.getRedoCount());
											InitDatasDaoImpl
													.submitElectronMainfestAgree(
															THIS, param);
										} catch (Exception e) {

										}
									}
								}).setNegativeButton("取消", null).show();

				break;
			case R.id.submit_noContract_button:
				final EditText inputServer = new EditText(THIS);
				new AlertDialog.Builder(THIS)
						.setTitle("是否确认不同意条款？")
						.setIcon(android.R.drawable.ic_dialog_info)
						.setView(inputServer)
						.setPositiveButton("不同意",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										try {
											if (inputServer.getText()
													.toString().length() > 0) {
												Map<String, Object> param = new HashMap<String, Object>();
												param.put("id", thisEleId);
												param.put("ship_id",
														spu.getShip_id());
												param.put("reason", inputServer
														.getText().toString());
												param.put("redoCount",
														spu.getRedoCount());
												InitDatasDaoImpl
														.submitElectronMainfestNotAgree(
																THIS, param);
											} else {
												FunctionOfActivity
														.makeToaskShow(THIS,
																"请填写“不同意”该合同的理由");
											}
										} catch (Exception e) {

										}
									}
								}).setNegativeButton("取消", null).show();

				break;
			case R.id.backToBeforeBt6:
				finish();
				break;
			case R.id.request_cancel_button:
				requestCancelButtonAction();

				break;
			default:
				break;
			}
		}

	};

	public String getIntentValue(String key) {
		try {
			return getIntent().hasExtra(key) == false ? "" : getIntent()
					.getStringExtra(key);
		} catch (Exception e) {

			return "";
		}
	}

	protected void requestCancelButtonAction() {
		final AlertDialog.Builder adB = new AlertDialog.Builder(THIS);
		LayoutInflater inflater = LayoutInflater.from(THIS);
		View view = inflater.inflate(R.layout.ele_remack_loading, null, false);
		adB.setView(view);
		final AlertDialog db = adB.create();
		// 设置全屏
		db.requestWindowFeature(Window.FEATURE_NO_TITLE);
		// 设置位置
		db.setView(view, 0, 0, 0, 0);
		Button submitRequestBt = (Button) view
				.findViewById(R.id.submitRequestBt);
		Button cancelBt = (Button) view.findViewById(R.id.cancelBt);
		final EditText remarkEt = (EditText) view.findViewById(R.id.remarkEt);
		cancelBt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				db.cancel();
			}
		});
		submitRequestBt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				new AlertDialog.Builder(THIS)
						.setTitle("是否申请取消合同？")
						.setIcon(android.R.drawable.ic_dialog_info)
						.setPositiveButton("是",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										try {
											Map<String, Object> param = new HashMap<String, Object>();
											param.put("ship", spu.getShip_id());
											param.put("eleId", thisEleId);
											param.put("reason", remarkEt
													.getText().toString());
											param.put("ownerConfirm",
													ownerConfirm);
											param.put("shipperConfirm",
													shipperConfirm);
											InitDatasDaoImpl
													.submitElectronMainfestRequestCancel(
															THIS, param);
										} catch (Exception e) {
										}
									}
								}).setNegativeButton("否", null).show();
				db.cancel();
			}
		});
		db.show();

	}

	private void initWebView(String eleId) {
		try {
			//
			String shipId = spu.getShip_id();
			uri = HttpUrlConstant.SHIPBIZ_BASE_URL
					+ HttpUrlConstant.TOONEELE_URI;
			uri = uri + "?eleId='" + eleId + "'" + "&ship='" + shipId + "'";
			webView = (WebView) findViewById(R.id.webview);
			// WebView加载web资源
			webView.loadUrl(uri);
			System.out.println("访问地址：-------" + uri);
		} catch (Exception e) {
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 请求结果处理
	 */
	@SuppressLint("HandlerLeak")
	public Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			try {
				pro.dismiss();
				Bundle data = msg.getData();
				if (!data.isEmpty()) {
					try {
						switch (msg.what) {
						case HttpUrlConstant.INIT_TOONEELE_BY_ID:
							FunctionOfActivity.makeToaskShow(THIS,
									data.getString("msg"));
							if ("isPass"
									.equals(data.getString("submit_result"))) {
								DBUtil.saveElectronManifestDbForOne(THIS,
										data.getString("result"));
								initView();
							} else {
								InitDatasDaoImpl
										.getElectronMainifestDatas(THIS);
							}
							break;
						default:
							break;
						}
					} catch (Exception e) {
						FunctionOfActivity.makeToaskShow(THIS, "操作异常");
					}
				}
			} catch (Exception e) {
			}
		};
	};

}
